package io.webchat.wdzl.controller;


import com.alibaba.fastjson.JSONObject;
import com.github.AopLog;
import io.webchat.annotation.Login;
import io.webchat.minio.MinloUploadService;
import io.webchat.utils.Constant;
import io.webchat.utils.JwtUtils;
import io.webchat.wdzl.bo.UserBO;
import io.webchat.wdzl.enums.OperatorFriendRequestTypeEnum;
import io.webchat.wdzl.enums.SearchFriendsStatusEnum;
import io.webchat.wdzl.pojo.*;
import io.webchat.wdzl.services.UserServices;
import io.webchat.wdzl.utils.FileUtils;
import io.webchat.wdzl.utils.IWdzlJSONResult;
import io.webchat.wdzl.utils.MD5Utils;
import io.webchat.wdzl.vo.FriendsRequestVO;
import io.webchat.wdzl.vo.MyFriendsVO;
import io.webchat.wdzl.vo.UserVo;
import lombok.Synchronized;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/user")
@AopLog(type = "请求相关参数记录",stackTraceOnErr = true)
public class UserController {


    @Autowired
    UserServices userServices;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    MinloUploadService minloUploadService;


    /**用户登录与注册一体化方法
     * @param user
     * @return
     */
    @PostMapping("/register")
    public IWdzlJSONResult registerOrLogin(@RequestBody User user){
        User userResult = userServices.queryUserNameIsExit(user.getUsername());
        if(userResult!=null) {//此用户存在，可登录
            return IWdzlJSONResult.error("用户名已存在");
        }
        user.setNickname(user.getUsername());
            user.setQrcode("");
            user.setPassword(MD5Utils.getPwd(user.getPassword()));
            user.setFaceImageBig("");
            userServices.insert(user);
        return IWdzlJSONResult.ok();
    }

    @PostMapping("/login")
    public IWdzlJSONResult login(@RequestBody User user){
        User userResult = userServices.queryUserNameIsExit(user.getUsername());
        if(userResult!=null) {//此用户存在，可登录
            if (!userResult.getPassword().equals(MD5Utils.getPwd(user.getPassword()))) {
                return IWdzlJSONResult.error("密码不正确");
            }else {
                Token tokenEntity = new Token();
                tokenEntity.setUserId(userResult.getId());
                tokenEntity.setUserName(userResult.getUsername());
                tokenEntity.setExpireTime(new Date().getTime()+jwtUtils.getExpire());
                String token = jwtUtils.generateToken(tokenEntity);
                tokenEntity.setToken(token);
                String jsonString = JSONObject.toJSONString(tokenEntity);
                redisTemplate.opsForValue().set(Constant.LOGON_TOKEN+userResult.getId(), jsonString,jwtUtils.getExpire(), TimeUnit.MILLISECONDS);
                LoginPojo loginPojo = new LoginPojo();
                loginPojo.setUserId(userResult.getId());
                loginPojo.setToken(token);
                loginPojo.setExpire(jwtUtils.getExpire());
                loginPojo.setLoginDate(new Date());
                loginPojo.setFaceImageBig(userResult.getFaceImageBig());
                loginPojo.setNickname(userResult.getNickname());
                loginPojo.setQrcode(userResult.getQrcode());
                loginPojo.setUsername(userResult.getUsername());

                return IWdzlJSONResult.ok().putValue(loginPojo);
            }
        }else {
            return IWdzlJSONResult.error("用户不存在");
        }
    }

    @PostMapping("/uploadFaceBase64")
    @Login
    public IWdzlJSONResult uploadFaceBase64(@RequestBody UserBO userBO){
        User result = null;
        try {
            //获取前端传过来的base64的字符串，然后转为文件对象在进行上传
            String base64Data = userBO.getFaceData();
            String userFacePath = "/Users/lijinping/Desktop/crow/"+userBO.getUserId()+"userFaceBase64.png";
            //调用FileUtils 类中的方法将base64 字符串转为文件对象
            FileUtils.base64ToFile(userFacePath, base64Data);
            MultipartFile multipartFile = FileUtils.fileToMultipart(userFacePath);
            //获取minlo上传图片的路径
            String url= minloUploadService.uploadImg(multipartFile.getName(),userFacePath);
            //更新用户头像
            User user = new User();
            user.setId(userBO.getUserId());
            user.setFaceImageBig(url);
            result = userServices.updateUserInfo(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return  IWdzlJSONResult.ok().putValue(result);
    }

    @PostMapping("/uploadFaceImg")
    @Login
    public IWdzlJSONResult uploadFaceImg(@RequestBody UserBO userBO){
        User result = null;
        try {
            //更新用户头像
            User user = new User();
            user.setId(userBO.getUserId());
            user.setFaceImageBig(userBO.getFaceData());
            result = userServices.updateUserInfo(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return  IWdzlJSONResult.ok().putValue(result);
    }

    @Login
    @GetMapping("/loginOut")
    public IWdzlJSONResult loginOut(@RequestParam("userId") String userId){
        redisTemplate.opsForValue().decrement(userId);
        return IWdzlJSONResult.ok();
    }


    //搜索好友的请求方法
    @Login
    @GetMapping("/searchFriend")
    public IWdzlJSONResult searchFriend(@RequestParam("myUserId") String myUserId,@RequestParam("friendUserName") String friendUserName){
        /**
         * 前置条件：
         * 1.搜索的用户如果不存在，则返回【无此用户】
         * 2.搜索的账号如果是你自己，则返回【不能添加自己】
         * 3.搜索的朋友已经是你好友，返回【该用户已经是你的好友】
         */
        Integer status = userServices.preconditionSearchFriends(myUserId,friendUserName);
        if(status== SearchFriendsStatusEnum.SUCCESS.status){
            User user = userServices.queryUserNameIsExit(friendUserName);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            return IWdzlJSONResult.ok().put("data",userVo);
        }else{
            String msg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IWdzlJSONResult.error(msg);
        }
    }


    //发送添加好友请求的方法
    @Login
    @GetMapping("/addFriendRequest")
    public IWdzlJSONResult addFriendRequest(@RequestParam("myUserId") String myUserId,@RequestParam("friendUserName") String friendUserName){
        if(StringUtils.isBlank(myUserId)|| StringUtils.isBlank(friendUserName)){
            return IWdzlJSONResult.error("好友信息为空");
        }

        /**
         * 前置条件：
         * 1.搜索的用户如果不存在，则返回【无此用户】
         * 2.搜索的账号如果是你自己，则返回【不能添加自己】
         * 3.搜索的朋友已经是你好友，返回【该用户已经是你的好友】
         */
        Integer status = userServices.preconditionSearchFriends(myUserId,friendUserName);
        if(status==SearchFriendsStatusEnum.SUCCESS.status){
            userServices.sendFriendRequest(myUserId,friendUserName);
        }else{
            String msg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IWdzlJSONResult.error(msg);
        }
        return IWdzlJSONResult.ok();
    }


    //好友请求列表查询
    @Login
    @GetMapping("/queryFriendRequest")
    public IWdzlJSONResult queryFriendRequest(@RequestParam("userId") String userId){
        List<FriendsRequestVO> friendRequestList = userServices.queryFriendRequestList(userId);
        return IWdzlJSONResult.ok().putValue(friendRequestList);
    }

    //好友请求处理映射my_friends
    @Login
    @Transactional
    @GetMapping("/operFriendRequest")
    public IWdzlJSONResult operFriendRequest(@RequestParam("acceptUserId") String acceptUserId,@RequestParam("sendUserId") String sendUserId,@RequestParam("operType") Integer operType){
        FriendsRequest friendsRequest = new FriendsRequest();
        friendsRequest.setAcceptUserId(acceptUserId);
        friendsRequest.setSendUserId(sendUserId);
        if(operType== OperatorFriendRequestTypeEnum.IGNORE.type){
            //满足此条件将需要对好友请求表中的数据进行删除操作
            userServices.deleteFriendRequest(friendsRequest);
        }else if(operType==OperatorFriendRequestTypeEnum.PASS.type){
            //满足此条件表示需要向好友表中添加一条记录，同时删除好友请求表中对应的记录
            userServices.passFriendRequest(sendUserId,acceptUserId);
        }
        //查询好友表中的列表数据
        List<MyFriendsVO> myFriends = userServices.queryMyFriends(acceptUserId);
        return IWdzlJSONResult.ok().putValue(myFriends);
    }

    /**
     * 好友列表查询
     * @param
     * @return
     */
    @Login
    @GetMapping("/myFriends")
    public IWdzlJSONResult myFriends(@RequestParam("userId") String userId){
        if (StringUtils.isBlank(userId)){
            return IWdzlJSONResult.error("用户id为空");
        }
        //数据库查询好友列表
        List<MyFriendsVO> myFriends = userServices.queryMyFriends(userId);
        return IWdzlJSONResult.ok().putValue(myFriends);
    }

    /**
     * 用户手机端获取未签收的消息列表
     * @param acceptUserId
     * @return
     */
    @Login
    @GetMapping("/getUnReadMsgList")
    public IWdzlJSONResult getUnReadMsgList(@RequestParam("acceptUserId") String acceptUserId){
        if(StringUtils.isBlank(acceptUserId)){
            return IWdzlJSONResult.error("接收者ID不能为空");
        }
        //根据接收ID查找为签收的消息列表
        List<ChatMsg> unReadMsgList = userServices.getUnReadMsgList(acceptUserId);
        return IWdzlJSONResult.ok().putValue(unReadMsgList);

    }





}
